package com.example.bilibili_miaosha.config;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.bilibili_miaosha.entity.User;
import com.example.bilibili_miaosha.service.IUserService;
import com.example.bilibili_miaosha.utils.CookieUtil;
import com.example.bilibili_miaosha.vo.RespBean;
import com.example.bilibili_miaosha.vo.RespBeanEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName AccessLimitInterceptor
 * @Description 接口限流注解的实现，拦截器
 * @Author 川
 * @Date 2022/4/9 15:29
 * @Version 1.0
 **/
@Component
public class AccessLimitInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    /**
    * @Description:  单纯的拦截器并不会传递相关变量
    * @Param: [request, response, handler] handler就是我们最后要处理的方法
    * @return: boolean
    * @Author: 弓川
    * @Date: 2022/4/9
    **/
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            User user= getUser(request, response);
            UserContext.setUser(user);   //这里将User交给UserContext，而后UserArg...Resolver返回了  UserContext.getUser()
//            user.setId(11111111111L);
//            user.setNickname("aaaaaa");
//            user.setPassword("123456");
            HandlerMethod hm = (HandlerMethod) handler;
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);//获取接口限流注解
            //如果没有使用该注解，accessLimit就为空，结束
            if (accessLimit == null) {
                return true;
            }
            //使用了注解的话
            int second = accessLimit.second();
            int maxCount = accessLimit.maxCount();
            boolean needLogin = accessLimit.needLogin();
            String key = request.getRequestURI();//key是保存在redis中的记录的key
            if (needLogin) {//登录判断
                if (user == null) {
                    render(response, RespBeanEnum.SESSION_ERROR);
                    return false;
                }
                key += ":" + user.getId();
            }
            ValueOperations valueOperations = redisTemplate.opsForValue();
            Integer count = (Integer) valueOperations.get(key);
            if (count == null) {
                valueOperations.set(key, 1, second, TimeUnit.SECONDS);
            } else if (count < maxCount) {
                valueOperations.increment(key);
            } else {
                render(response, RespBeanEnum.ACCESS_LIMIT_REACHED);
                return false;
            }
        }
        return true;
    }


    /**
     * 功能描述: 构建返回对象
     *
     * @param:
     * @return: 乐字节：专注线上IT培训
     * 答疑老师微信：lezijie
     * @since: 1.0.0
     * @Author:zhoubin
     */
    private void render(HttpServletResponse response, RespBeanEnum respBeanEnum) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        RespBean respBean = RespBean.error(respBeanEnum);
        out.write(new ObjectMapper().writeValueAsString(respBean));
        out.flush();
        out.close();
    }

    /**
     * 功能描述: 获取当前登录用户
     *
     * @param:
     * @return: 乐字节：专注线上IT培训
     * 答疑老师微信：lezijie
     * @since: 1.0.0
     * @Author:zhoubin
     */
    private User getUser(HttpServletRequest request, HttpServletResponse response) {
//        System.out.println("获取当前USER");
        String ticket = CookieUtil.getCookieValue(request, "userTicket");
        if (StringUtils.isEmpty(ticket)) {
            return null;
        }
        return userService.getUserByCookie(ticket, request, response);
    }
}

